<template>
  <div>
    <input ref="excel-upload-input" class="excel-upload-input" type="file" accept=".xlsx, .xls" @change="handleClick">
    <div class="drop" @drop="handleDrop" @dragover="handleDragover" @dragenter="handleDragover">
      拖拽文件到这里
      <el-button :loading="loading" style="margin-left:16px;" size="mini" type="primary" @click="handleUpload">
        上传
      </el-button>
    </div>
  </div>
</template>

<script>
import XLSX from 'xlsx'
import request from '@/utils/request'
import { getData} from '@/api/table'

export default {
  props: {
    beforeUpload: Function, // eslint-disable-line
    onSuccess: Function// eslint-disable-line
  },
  data() {
    return {
      loading: false,
      excelData: {
        results: null,
        total: 0
      },
      total:0,
      list: [],//列表
      queryParams:{
        pageNum:1,
        pageSize:10,
      },
      listLoading: true
    }
  },
  methods: {
    generateData( results) {
      this.excelData.results = results
      this.excelData.total = this.total
      this.onSuccess && this.onSuccess(this.excelData)
    },
    handleDrop(e) {
      e.stopPropagation()
      e.preventDefault()
      if (this.loading) return
      const files = e.dataTransfer.files
      if (files.length !== 1) {
        this.$message.error('Only support uploading one file!')
        return
      }
      const rawFile = files[0] // only use files[0]

      if (!this.isExcel(rawFile)) {
        this.$message.error('Only supports upload .xlsx, .xls, .csv suffix files')
        return false
      }
      this.upload(rawFile)
      e.stopPropagation()
      e.preventDefault()
    },
    handleDragover(e) {
      e.stopPropagation()
      e.preventDefault()
      e.dataTransfer.dropEffect = 'copy'
    },
    //调用点击事件
    handleUpload() {
      this.$refs['excel-upload-input'].click()
    },

   async handleClick(e) {
      const files = e.target.files
      const rawFile = files[0]  // 获取第一个文件
      
      if (!rawFile) return
      
      // 创建 FormData 对象（重要！）
      const formData = new FormData()
      formData.append('file', rawFile)  // 字段名需要和后端一致
      
      // 发送请求（示例使用 axios）
      this.loading = true
     await request.post('/file/fileUpdate', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'  // 必须设置正确的请求头
        }
      }).then(res => {
        console.log('上传成功:', res)
        this.$message.success('文件上传成功')
        // 如果需要处理 Excel 数据，可以在这里调用解析逻辑
        this.readerData(rawFile)
      }).catch(err => {
        console.error('上传失败:', err)
        this.$message.error('文件上传失败')
      }).finally(() => {
        this.loading = false
      })
    },


    upload(rawFile) {
      this.$refs['excel-upload-input'].value = null // fix can't select the same excel

      if (!this.beforeUpload) {
        this.readerData(rawFile) //处理数据
        return
      }
      const before = this.beforeUpload(rawFile)
      if (before) {
        this.readerData(rawFile)
      }
    },
    readerData(rawFile) {
      this.loading = true
      getData(this.queryParams).then(response => {
        this.list = response.data.rows
        this.total= response.data.total;
        this.listLoading = false
        this.generateData(this.list)
      })
      

      // return new Promise((resolve, reject) => {
      //   const reader = new FileReader()
      //   reader.onload = e => {
      //     const data = e.target.result
      //     const workbook = XLSX.read(data, { type: 'array' })
      //     const firstSheetName = workbook.SheetNames[0]
      //     const worksheet = workbook.Sheets[firstSheetName]
      //     const header = this.getHeaderRow(worksheet)
      //     const results = XLSX.utils.sheet_to_json(worksheet)
      //     this.generateData({ header, results })
      //     this.loading = false
      //     resolve()
      //   }
      //   reader.readAsArrayBuffer(rawFile)
      // })
    },

   
   
    isExcel(file) {
      return /\.(xlsx|xls|csv)$/.test(file.name)
    }
  }
}
</script>

<style scoped>
.excel-upload-input{
  display: none;
  z-index: -9999;
}
.drop{
  border: 2px dashed #bbb;
  width: 600px;
  height: 160px;
  line-height: 160px;
  margin: 0 auto;
  font-size: 24px;
  border-radius: 5px;
  text-align: center;
  color: #bbb;
  position: relative;
}
</style>
